﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using ZH.GPT.Infrastructures.Enum;
using System;
using System.Collections.Generic;
using System.Text;

namespace ZH.GPT.Infrastructures.Extension
{
    /// <summary>
    /// DBContext工厂
    /// </summary>
    public class DbContextFactory : IDbContextFactory
    {
        /// <summary>
        /// DBContext
        /// </summary>
        private DbContext _dbContext = null;

        /// <summary>
        /// 
        /// </summary>
        private DbConnections _dbConnections = null;

        /// <summary>
        ///工厂，注入DbContext，和使用IOptionsMonitor注入连接地址
        /// </summary>
        /// <param name="context">DbContext</param>
        /// <param name="options">连接地址</param>
        public DbContextFactory(DbContext context, IOptionsMonitor<DbConnections> options)
        {
            _dbConnections = options.CurrentValue;
            this._dbContext = context;
        }

        /// <summary>
        /// 更换连接
        /// </summary>
        /// <param name="dbOption">选择主从库</param>
        /// <returns></returns>
        public DbContext GetDbContext(DBOption dbOption)
        {
            switch (dbOption)
            {
                case DBOption.Master:
                    ToMaster();
                    break;  
                case DBOption.Slave:
                    ToSlave();
                    break; 
                default:
                    break;
            }
            return _dbContext;
        }
         
        /// <summary>
        /// 更换成主库连接
        /// </summary>
        /// <returns></returns>
        private void ToMaster()
        {
            _dbContext.GetDbContext(_dbConnections.MasterConnection); 
        }

        /// <summary>
        /// 更换成从库连接，并使用随机策略提取连接
        /// </summary>
        /// <returns></returns>
        private void ToSlave()
        {
            string conn = string.Empty;
            {
                //随机
                int Count = _dbConnections.SlaveConnectionList.Count;
                int index = new Random().Next(0, Count);
                conn = _dbConnections.SlaveConnectionList[index];
            } 
            _dbContext.GetDbContext(conn);
        }

    }
}
